package com.cedric.component;

import com.alibaba.fastjson.JSON;
import com.cedric.entity.DelayJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @program: delay-queue
 * @description: 队列
 * @author: 史偕成
 * @create: 2021/09/26 21:30
 **/
@Slf4j
@Component
public class ReadyQueue {

    @Autowired
    private RedisTemplate redisTemplate;

    private final static String NAME = "process.queue";

    /**
     * 获取key
     *
     * @param topic
     * @return
     */
    private String getKey(String topic) {
        return NAME + topic;
    }

    /**
     * 获取队列
     *
     * @return
     */
    private BoundListOperations getQueue(String topic) {
        return redisTemplate.boundListOps(getKey(topic));
    }

    /**
     * 设置任务
     * @param job
     */
    public void pushJob(DelayJob job) {
        log.info("[队列添加任务]: {}", JSON.toJSONString(job));
        BoundListOperations queue = getQueue(job.getTopic());
        queue.leftPush(job);
    }


    /**
     * 移除并获得任务
     * @param topic
     * @return
     */
    public DelayJob popJob(String topic) {
        BoundListOperations listOperations = getQueue(topic);
        Object o = listOperations.leftPop();
        if (o instanceof DelayJob) {
            log.info("执行队列取出任务:{}", JSON.toJSONString(o));
            return (DelayJob) o;
        }
        return null;
    }
}
